﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Sencha.Serialization.Bson.Serializers
{
    public sealed class BsonSymbolSerializer : TypeSerializer<BsonSymbol>
    {
        private static string DefaultCode = "";

        public override BsonSymbol Deserialize(IJsonReader reader)
        {
            if (reader == null)
                throw new ArgumentNullException("reader");

            if (reader is IBsonReader)
				return this.DeserializeBson(reader as IBsonReader);

            reader.ReadObjectBegin();
			var symbol = reader.ReadMember<string>("$symbol");
            reader.ReadObjectEnd(false);

            var value = new BsonSymbol(symbol);
            return value;
        }
		private BsonSymbol DeserializeBson(IBsonReader reader)
        {
			if (reader.Token != BsonToken.Symbol)
				throw new Exceptions.UnexpectedBsonToken(reader, BsonToken.Symbol);

			var value = (BsonSymbol)reader.Value.Raw;
            return value;
        }

        public override void Serialize(IJsonWriter writer, BsonSymbol value)
        {
            if (writer == null)
                throw new ArgumentNullException("writer");

            if (value == null)
            {
                writer.WriteNull();
                return;
            }

            if (writer is IBsonWriter)
            {
				this.SerializeBson(writer as IBsonWriter, value);
                return;
            }

            writer.WriteObjectBegin();
			writer.WriteMember<string>("$symbol", (string)value);
            writer.WriteObjectEnd();
        }
		private void SerializeBson(IBsonWriter writer, BsonSymbol value)
        {
            if (value == null)
                throw new ArgumentNullException("value");
            if (writer == null)
                throw new ArgumentNullException("writer");

            writer.Write(BsonToken.Symbol, value);            
        }
    }
}
